package com.zzh.bc.modules.jks.controller;

import com.zzh.bc.base.BaseVo;
import com.zzh.bc.model.JksModel;
import com.zzh.bc.modules.jks.service.JksService;
import com.zzh.bc.modules.jks.service.impl.JksServiceImpl;
import com.zzh.bc.modules.jks.vo.JksVo;
import com.zzh.bc.utils.FileManager;
import com.zzh.bc.utils.RequestParamUtils;
import com.zzh.bc.utils.RespParamUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class JksController extends HttpServlet {

    JksService jksService;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        checkService();
        Optional<JksVo> jksVo = RequestParamUtils.safeRequestBodyParams(req, JksVo.class);
        if (jksVo.isPresent()) {
            JksVo vo = jksVo.get();
            if (vo.getMethod().equals(BaseVo.JKS_ADD)) {
                addJks(req.getInputStream(), vo, resp);
            } else {
                findJksAll(vo, resp);
            }

        } else {
            RespParamUtils.respJsonError(resp);
        }

    }

    private void checkService() {
        if (jksService == null){
            jksService = new JksServiceImpl();
        }
    }

    private void findJksAll(JksVo vo,HttpServletResponse resp) {
        List<JksModel> all = jksService.findAll(vo.getPage());
        RespParamUtils.respJsonOk(resp, all);
    }

    private void addJks(ServletInputStream sis, JksVo vo, HttpServletResponse resp) {

        try {
            FileUtils.copyToFile(sis, new File(FileManager.FILE_ROOT_PATH, System.currentTimeMillis()+".jks"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public static void main(String[] args) {
    }

}
